package org.login.handler;

import akka.actor.typed.ActorRef;
import lombok.extern.slf4j.Slf4j;
import org.common.akka.message.BaseMsg;
import org.common.akka.message.PushToClientMsg;
import org.common.akka.message.RoleLoginMsg;
import org.common.dispatcher.CMD;
import org.common.handler.BaseProtoHandler;
import org.common.netty.Pack;
import org.common.utils.SpringUtils;
import org.login.akka.ConnectActorManager;
import org.login.obj.GameServerContext;
import org.protobuf.InnerServerMsg;
import org.protobuf.ProtoEnumMsg;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class InnerServerProtoHandler extends BaseProtoHandler {

    /**
     * 角色登录回调
     */
    @CMD(ProtoEnumMsg.CMD.ID.NOTIFY_GAME_ROLE_LOGIN_VALUE)
    public Pack notifyGameRoleLogin(GameServerContext gc, InnerServerMsg.G2LRoleLogin up) {
        long roleId = up.getRoleId();
        long accountId = up.getAccountId();
        log.info("角色登录GameServer成功, roleId = {}, accountId = {}", roleId, accountId);
        ConnectActorManager connectActorManager = SpringUtils.getBean(ConnectActorManager.class);
        ActorRef<BaseMsg> connectActor = connectActorManager.getConnectActorByAccountId(accountId);

        RoleLoginMsg roleLoginMsg = new RoleLoginMsg();
        roleLoginMsg.setRoleId(roleId);
        roleLoginMsg.setAccountId(accountId);
        connectActor.tell(roleLoginMsg);

        return null;
    }

    /**
     * 游戏服推送协议到客户端
     */
    @CMD(ProtoEnumMsg.CMD.ID.PUSH_PROTO_TO_CLIENT_VALUE)
    public Pack pushProtoToClient(GameServerContext gc, InnerServerMsg.G2LClientDownMsg up) {
        long accountId = up.getAccountId();
        ConnectActorManager connectActorManager = SpringUtils.getBean(ConnectActorManager.class);
        ActorRef<BaseMsg> connectActor = connectActorManager.getConnectActorByAccountId(accountId);
        if (connectActor == null) {
            log.error("下行数据找不到对应地connectActor, accountId={}", accountId);
            return null;
        }
        PushToClientMsg pushToClientMsg = new PushToClientMsg(up.getData().toByteArray());
        connectActor.tell(pushToClientMsg);
        return null;
    }
}
